"""知识点更新相关视图

此模块包含用于更新知识点的视图函数和相关功能。
"""
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from core.models import KnowledgePoint, TeacherSubjectAssignment
from core.forms.knowledge_point_form import KnowledgePointForm
from core.utils import log_operation


def _has_subject_permission(request: HttpRequest, subject_id: int) -> bool:
    """检查用户是否有权限操作指定学科

    Args:
        request: HTTP请求对象
        subject_id: 学科ID

    Returns:
        bool: 用户是否有权限
    """
    return TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=subject_id
    ).exists()


@login_required
def knowledge_point_update(request: HttpRequest, pk: int) -> HttpResponse:
    """更新知识点

    该视图函数处理知识点的更新操作，包括显示表单和处理表单提交。
    验证用户是否有权限操作指定知识点所属的学科，并记录操作日志。

    Args:
        request: HTTP请求对象
        pk: 知识点的主键ID

    Returns:
        HttpResponse: 渲染的更新表单页面或重定向到知识点列表
    """
    knowledge_point = get_object_or_404(KnowledgePoint, pk=pk)
    chapter = knowledge_point.chapter

    # 验证用户是否有权限操作此知识点所属的学科
    if not _has_subject_permission(request, chapter.subject_id):
        return render(request, 'knowledge_point/permission_denied.html', status=403)

    if request.method == 'POST':
        form = KnowledgePointForm(request.POST, instance=knowledge_point)
        if form.is_valid():
            with transaction.atomic():
                old_name = knowledge_point.name
                knowledge_point = form.save()

            log_operation(
                user=request.user,
                operation_type='update',
                content_type='KnowledgePoint',
                object_id=knowledge_point.id,
                object_name=knowledge_point.name,
                request=request,
                details=f'更新知识点: {old_name} -> {knowledge_point.name}'
            )

            messages.success(request, '知识点更新成功')
            return redirect('core:knowledge_point_list', chapter_id=chapter.id)
    else:
        form = KnowledgePointForm(instance=knowledge_point)

    return render(request, 'knowledge_point/knowledge_point_form.html', {
        'form': form,
        'chapter': chapter,
        'title': '更新知识点'
    })